<template>
	<view class="login-box"
		:style="{backgroundImage: `url(${h5MiniAssets('/index/login-bg.png')})`, backgroundSize: '100% auto'}">
		<template v-if="isPhoneLogin">
			<view class="flex items-center justify-between" style="padding: 40rpx 26rpx;font-weight: bold;">
				<view class="flex items-center justify-center" style="padding-left: 24px;flex: 1 1 0 ;width: 200rpx;">
					<image :src="pInfo.logo" mode="heightFix" style="height: 50rpx;width: 50rpx;margin-right: 14rpx;">
					</image>
					<text style="font-size: 34rpx;font-weight: bold;line-height: 40rpx;">登录{{ pInfo.name }}</text>
				</view>
				<view class="center" style="color: gainsboro;" @click="$emit('close')">
					<uni-icons type="closeempty" color="#999999" size="24"></uni-icons>
				</view>
			</view>

			<view class="" style="padding: 0rpx 26rpx 32rpx;">
				<view class="flex items-center justify-between" style="border-bottom: 3rpx solid #ECECEC;padding: 30rpx 0;">
					<view class="flex items-center" style="flex:1;width: 200rpx;margin-right: 20rpx;">
						<view class="" style="margin-right: 20rpx;">
							+86
						</view>
						<input :adjust-position="false" @focus="getKeyboardHeight" @blur="recoverHeight" maxlength="11"
							v-model="phone" type="number" style="flex: 1;width: 140rpx;" placeholder="请输入手机号" />
					</view>
					<view class="" :style="{color: time>0 ? '#999999' : '#1277FF'}" @click="getCode">
						{{ time >0 ? `${time}s` : '获取验证码' }}
					</view>
				</view>
				<view class="flex items-center justify-between" style="border-bottom: 3rpx solid #ECECEC;padding: 30rpx 0;">
					<input  :adjust-position="false" @focus="getKeyboardHeight" @blur="recoverHeight" v-model="code"
						style="width: 100%;" placeholder="请输入验证码" />
				</view>

				<view class="flex items-center" style="margin-top: 42rpx;">
					<view v-if="!isAgree" @click="isAgree = true" class=""
						style="display: flex;justify-content: center; align-items: center;margin-right: 6rpx;">
						<uni-icons type="circle" size="42rpx" color="#1277FF"></uni-icons>
					</view>
					<view v-else class=""
						@click="isAgree = false"
						style="display: flex;justify-content: center; align-items: center;color: #1277FF; margin-right: 6rpx;">
						<uni-icons type="checkbox" size="42rpx" color="#1277FF"></uni-icons>
					</view>
					<text style="font-size: 26rpx;"><text @click="isAgree = true">我已阅读并同意</text><text
							@click="useProtocolLink().toUserServicesAgreement()" style="color: #1277FF;">《用户服务协议》</text> <text
							@click="useProtocolLink().toPrivacyPolicy()" style="color: #1277FF;">《隐私协议》</text></text>
				</view>

				<button style="margin-top: 40rpx;" class="btn-nostyle login-button" @click="phoneLogin">
					立即登录
				</button>
				<view class="" style="text-align: center;color: #666666; margin-top: 30rpx;">
					<text @click="isPhoneLogin = false">一键快捷登录</text>
				</view>

				<view class="height-box" :style="{height: `${keyboardHeight}px`}">

				</view>
			</view>

		</template>

		<template v-else>
			<view class="flex items-center justify-between" style="padding: 40rpx 26rpx;font-weight: bold;">
				<view class="">
					登录方式选择及隐私政策告知
				</view>
				<view class="center" style="color: gainsboro;" @click="$emit('close')">
					<uni-icons type="closeempty" color="#999999" size="24"></uni-icons>
				</view>
			</view>

			<view class="" style="padding: 0 26rpx 32rpx;">
				<view class="" style="padding: 4rpx 0;font-size: 28rpx;color: #666666;">
					<text>为了您正常的使用我们的小程序服务，我们需要处理您的个人信息，具体详见</text>
					<text style="color: #1277FF;" @click="useProtocolLink().toPrivacyPolicy()">《隐私政策》</text>
					<text>。在您未确认</text>
					<text style="color: #1277FF;" @click="useProtocolLink().toPrivacyPolicy()">《隐私政策》</text>
					<text>前，我们不会搜集您的任何信息。</text>
				</view>
				<view class="flex items-center" style="margin-top: 42rpx;">
					<view v-if="!isAgree" @click="isAgree = true" class=""
						style="display: flex;justify-content: center; align-items: center;margin-right: 6rpx;">
						<uni-icons type="circle" size="42rpx" color="#1277FF"></uni-icons>
					</view>
					<view v-else class=""
						@click="isAgree = false"
						style="display: flex;justify-content: center; align-items: center;color: #1277FF; margin-right: 6rpx;">
						<uni-icons type="checkbox" size="42rpx" color="#1277FF"></uni-icons>
					</view>
					<text style="font-size: 26rpx;"><text @click="isAgree = true">我已阅读并同意</text><text
							@click="useProtocolLink().toUserServicesAgreement()" style="color: #1277FF;">《用户服务协议》</text> <text
							@click="useProtocolLink().toPrivacyPolicy()" style="color: #1277FF;">《隐私协议》</text></text>
				</view>

				<button @click="btnTaphandler" style="margin-top: 40rpx;" class="btn-nostyle login-button"
					open-type="getPhoneNumber" @getphonenumber="submit">
					一键登录
				</button>
				<view class="" style="text-align: center;color: #666666; margin-top: 30rpx;">
					<text @click="isPhoneLogin = true">输入手机号登录</text>
				</view>
			</view>

		</template>
	</view>
</template>

<script>
	import {
		useProtocolLink
	} from '../../../configs/protocol_link'
	import {
		getChannelCode
	} from '../../../utils/request'
	import {
		loginApi,
		sendSmsCodeApi
	} from '../../../api/user'
	import {
		h5Url,
		h5MiniAssets,
		productInfo
	} from '../../../configs/env.config'

	export default {
		data() {
			return {
				isAgree: false,
				isPhoneLogin: false,
				phone: '',
				code: '',
				time: 0,
				interval: 0,
				keyboardHeight: 0,
				recoverTimeout: 0,
			}
		},
		computed: {
			pInfo(){
				return productInfo
			}
		},
		destroyed() {
			clearInterval(this.interval)
		},
		methods: {
			useProtocolLink,
			h5MiniAssets,
			// input聚焦时，获取键盘高度
			getKeyboardHeight(e) {
				clearTimeout(this.recoverTimeout)
				this.keyboardHeight = e.detail.height >0 ? 200: 0
			},
			// input失焦时，恢复原来位置
			recoverHeight(e) {
				this.recoverTimeout = setTimeout(() => {
					this.keyboardHeight = 0
				}, 200)
			},
			async phoneLogin() {
				if (!this.phone) {
					return uni.showToast({
						title: '请输入手机号',
						icon: 'none'
					})
				}
				if (!/^[1][2,3,4,5,6,7,8,9][0-9]{9}$/.test(this.phone)) {
					return uni.showToast({
						title: '手机号格式不正确',
						icon: 'none'
					})
				}
				if (!this.code) {
					return uni.showToast({
						title: '请输入验证码',
						icon: 'none'
					})
				}

				if (!this.isAgree) {
					return uni.showToast({
						title: '请先同意协议',
						icon: 'none'
					})
				}

				const channelCode = await getChannelCode()
				uni.showLoading()
				const res = await loginApi({
					loginType: 0,
					mobile: this.phone,
					loginCode: this.code
				}).catch(e => {
					console.log()
					return uni.showToast({
						title: e.message || '请求错误',
						icon: 'none'
					})
					return Promise.reject(e)
				}).finally(() => {
					uni.hideLoading()
				})
				const token = res.data.token
				const h5UrlHandler = `${h5Url}/?ch=${channelCode}&deviceId=${uni.getDeviceInfo().deviceId}&token=${token}`

				uni.navigateTo({
					url: `/pages/webview/webview?url=${encodeURIComponent(h5UrlHandler)}`
				})

				this.$emit('close')

			},
			async getCode() {
				if (this.time > 0) return;
				if (!this.phone) {
					return uni.showToast({
						title: '请输入手机号',
						icon: 'none'
					})
				}
				if (!/^[1][2,3,4,5,6,7,8,9][0-9]{9}$/.test(this.phone)) {
					return uni.showToast({
						title: '手机号格式不正确',
						icon: 'none'
					})
				}
				uni.showLoading()
				await sendSmsCodeApi({
					oType: 0,
					mobile: this.phone,
				}).finally(() => uni.hideLoading())
				this.time = 60
				this.interval = setInterval(() => {
					if (--this.time <= 0) clearInterval(this.interval)
				}, 1000)
			},
			async submit(e) {
				uni.hideLoading()
				console.log(e)
				console.log(e.detail.code) // 动态令牌
				console.log(e.detail.errMsg) // 回调信息（成功失败都会返回）
				console.log(e.detail.errno) // 错误码（失败时返回）

				const channelCode = await getChannelCode()

				if (e.type !== 'getphonenumber') return;
				if (e.detail.errMsg !== 'getPhoneNumber:ok') {
					console.log('用户拒绝了')
					this.isPhoneLogin = true
					// const h5UrlHandler = `${h5Url}/?ch=${channelCode}&deviceId=${uni.getDeviceInfo().deviceId}`

					// uni.navigateTo({
					// 	url: `/pages/webview/webview?url=${encodeURIComponent(h5UrlHandler)}`
					// })
					// this.$emit('close')
					return;
				}

				const mobileCode = e.detail.code;


				// uni.showLoading()

				const loginCode = await this.loginCodeGet()

				// console.log({
				// 	loginType: 8,
				// 	mobile: mobileCode,
				// 	loginCode: loginCode
				// })
				// return;

				const res = await loginApi({
					loginType: 8,
					mobile: mobileCode,
					loginCode: loginCode
				})
				const token = res.data.token
				const h5UrlHandler = `${h5Url}/?ch=${channelCode}&deviceId=${uni.getDeviceInfo().deviceId}&token=${token}`

				uni.navigateTo({
					url: `/pages/webview/webview?url=${encodeURIComponent(h5UrlHandler)}`
				})
				this.$emit('close')

				console.log(res)
			},
			loginCodeGet() {
				return new Promise((resolve, reject) => {
					uni.login({
						provider: 'weixin', //使用微信登录
						success: function(loginRes) {
							resolve(loginRes.code)
						},
						fail: reject
					})
				})
			},
			btnTaphandler() {
				this.isAgree = true
				uni.showLoading()
			}
		}
	}
</script>

<style lang="scss" scoped>
	.login-box {
		background-repeat: no-repeat;
	}

	.height-box {
		height: 0;
		transition-duration: 300ms;
	}

	.login-button {
		width: 100%;
		margin: auto;
		background-color: #1277FF;
		color: #fff;
		border-radius: 999999px;
		padding: 26rpx;
		font-size: 36rpx;
		font-weight: 500;
	}
</style>